package com.hrbu.mp.generator.controller;


import com.hrbu.mp.generator.bean.User;
import com.hrbu.mp.generator.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tanyajun
 * @since 2021-04-01
 */
@Controller
public class UserController {
    @Autowired
    IUserService userService;
    @GetMapping("users")
    public String toUsersPage(Model model){
        List<User> list = userService.list();
        model.addAttribute("userList",list);
        return "users";
    }

    /**
     * 前往添加用户页面
     * @param model
     * @return
     */
    @GetMapping("add")
    public String toaddFrom(Model model){
        model.addAttribute("url","add");
        model.addAttribute("title","添加用户");
        return "baseform";
    }
    @GetMapping("del")
    public String del(Integer id){
        boolean b = userService.removeById(id);
        System.out.println(b ? "删除成功" : "删除失败");
        return "redirect:users";
    }

    @GetMapping("edit")
    public String toEditFrom(Model model,@RequestParam("id") Integer id){
        model.addAttribute("url","edit");
        model.addAttribute("title","更新用户信息");
        User user = userService.getById(id);
        model.addAttribute("user",user);
        return "baseform";
    }
    @PostMapping("add")
    public String add(User user){
        System.out.println("添加操作: " + user);
        boolean isSave = userService.save(user);
        System.out.println(isSave ? "添加成功" : "添加失败");
        return "redirect:users";
    }
    @PostMapping("edit")
    public String edit(User user){
        System.out.println("更新操作: " + user);
        boolean isUpdate = userService.updateById(user);
        System.out.println(isUpdate ? "更新成功" : "更新失败");
        return "redirect:users";
    }
}

